package srv

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/beans"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/xids"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/dao"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/enums"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/model"
	"gorm.io/gorm"
)

func ReportResultColumninit() {
	srv := &ReportResultColumnSrv{}
	err := beans.ProvideBean(srv)
	asserts.Nil(err, err)
}

type ReportResultColumnSrv struct {
	BaseSrv
	*dao.ReportResultColumnDao `inject:""`
	Db                         *gorm.DB `inject:""`
}

// 通过reportId获取
func (s *ReportResultColumnSrv) GetByReportId(ctx context.Context, db *gorm.DB, reportId string) ([]model.ReportResultColumn, error) {
	var result []model.ReportResultColumn
	err := db.Model(&model.ReportResultColumn{}).Where("report_id = ?", reportId).Find(&result).Error
	return result, err
}

// 通过reportId和attributeName获取
func (s *ReportResultColumnSrv) GetByReportIdAndAttributeName(ctx context.Context, db *gorm.DB, reportId, attributeName string) (*model.ReportResultColumn, error) {
	result := model.ReportResultColumn{}
	err := db.Model(&model.ReportResultColumn{}).
		Where("report_id = ?", reportId).
		Where("attribute_name = ?", attributeName).
		Take(&result).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	return &result, err
}

// 插入报表返回结果
func (s *ReportResultColumnSrv) InsertResultColumn(ctx context.Context, db *gorm.DB, reportID string, columnName string) error {
	e := &model.ReportResultColumn{
		ReportResultColumnId: xids.GetXid(ctx),
		ReportId:             reportID,
		Type:                 enums.BiResultType.Text(),
		Name:                 columnName,
		AttributeName:        columnName,
		IsShow:               true,
	}
	err := s.Insert(ctx, db, e)
	return err
}

func (s *ReportResultColumnSrv) RemoveByReportId(ctx context.Context, tx *gorm.DB, reportId string) error {
	err := tx.Model(s.Model.GetModel()).Where("report_id = ?", reportId).Delete(s.Model.GetModel()).Error
	return err
}
